package com.itheima.web;

import com.itheima.web.mapper.UserMapper1;
import com.itheima.pojo.user;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.调用mybatis完成查询
        //2.1.加载mybatis的核心配置文件,获取sqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2.2获取sqlSession对象,执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //2.3执行sql方法
        UserMapper1 mapper = sqlSession.getMapper(UserMapper1.class);
        user user = mapper.SelectAll(username, password);
        //2.4释放sql资源
        sqlSession.close();

        //设置字符集
        response.setContentType("text/html:charset=UTF-8");
        //获取输出流
        PrintWriter writer = response.getWriter();
        //3.判断user释放为null
        if (user != null) {
            //登录成功
            writer.write("<h1>登录成功</h1>");
        }else {
            //登录失败
            writer.write("<h1>登录失败</h1>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
